@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

REM ==============================================
REM build_android_apk.bat
REM Purpose: Fetch code and build Android APK with Unity on Windows
REM 
REM Usage:
REM   build_android_apk.bat <DEBUG|RELEASE> <branch> <clean:true|false> <projectPath> <unityPath> [logFile]
REM Arguments:
REM   - buildType   : DEBUG or RELEASE
REM   - branch      : Git branch name, e.g., master
REM   - clean       : true/false, whether to clean caches and old artifacts
REM   - projectPath : Unity project directory (contains Assets/Packages, etc.)
REM   - unityPath   : Path to Unity.exe (e.g., C:\Program Files\Unity\Hub\Editor\2023.3.51f1c1\Editor\Unity.exe)
REM   - logFile     : Optional, output path for Unity -logFile (omit the flag if empty)
REM ==============================================

set "buildType=%~1"
set "branch=%~2"
set "clean=%~3"
set "projectPath=%~4"
set "unity=%~5"
set "logFile=%~6"
set "LOG_TAG=[BUILD]"
set "logSwitch="
if not "%logFile%"=="" (
  set "logSwitch=-logFile %logFile%"
)

if /I not "%buildType%"=="DEBUG" if /I not "%buildType%"=="RELEASE" (
  call :log "Invalid parameter: buildType must be DEBUG or RELEASE"
  exit /b 1
)

if "%branch%"=="" (
  call :log "Invalid parameter: branch must be specified"
  exit /b 1
)

if "%projectPath%"=="" (
  call :log "Invalid parameter: projectPath and unityPath are required"
  exit /b 1
)
if "%unity%"=="" (
  call :log "Invalid parameter: unityPath is required"
  exit /b 1
)

cd /d "%projectPath%"

::: Update Code
call :log "Update Code Start"
git checkout "%branch%"
if errorlevel 1 exit /b 1
git fetch origin
if errorlevel 1 exit /b 1
git pull
:::git reset --hard "origin/%branch%"
if errorlevel 1 exit /b 1
call :log "Update Code Finish"

::: Check Changed
call :log "Check Changed"
set "buildDir=%projectPath%\Build"
set "curr_buildId=%buildDir%\build_id_%buildType%.txt"
set "last_buildId=%buildDir%\build_id_%buildType%_last.txt"
set "destApk=%projectPath%\Build\Android\%buildType%.apk"
if not exist "%buildDir%" mkdir "%buildDir%"

git log -1 --format=%%h "origin/%branch%" > "%curr_buildId%" 2>nul

if exist "%last_buildId%" if exist "%destApk%" (
  fc /b "%curr_buildId%" "%last_buildId%" >nul
  if errorlevel 1 (
    del /f /q "%destApk%" 2>nul
  ) else (
    call :log "APK exists and up to date; no build needed"
    exit /b 0
  )
)
call :log "End Check Changed"

if /I "%clean%"=="true" (
  rmdir /s /q "%projectPath%\Assets\StreamingAssets" 2>nul
  rmdir /s /q "%projectPath%\Build\Android\%buildType%" 2>nul
)

::: Prebuild
 call :log "Prebuild Start"
  "%unity%" -buildTarget Android -batchmode -nographics -quit -projectPath "%projectPath%" -executeMethod BuildTool.BuildCommand.PreBuild %logSwitch%
  if errorlevel 1 exit /b 1
  call :log "Prebuild Finish"

::: BuildApk
call :log "BuildApk Start"
"%unity%" -batchmode -nographics -quit -projectPath "%projectPath%" -executeMethod BuildTool.BuildCommand.BuildAPK %logSwitch%
if errorlevel 1 exit /b 1
call :log "BuildApk Finish"

::: Resolve srcApk generated by BuildAPK
set "apkSearchRoot=%projectPath%\Build\Android\%buildType%"
set "srcApk="

if defined SRC_APK (
  set "srcApk=%SRC_APK%"
) else (
  for /f "delims=" %%F in ('dir /b /a-d /o-d "%apkSearchRoot%\*.apk" 2^>nul') do (
    if not defined srcApk (
      set "srcApk=%apkSearchRoot%\%%F"
    )
  )
)

if not defined srcApk (
  call :log "APK not found at %srcApk%"
  exit /b 1
)
if not exist "%srcApk%" (
  call :log "APK not found at %srcApk%"
  exit /b 1
)

if not exist "%projectPath%\Build\Android" mkdir "%projectPath%\Build\Android"
copy /Y "%srcApk%" "%destApk%" >nul
copy /Y "%curr_buildId%" "%last_buildId%" >nul
call :log "APK Output: %destApk%"
call :log "BuildAPK Finished"

endlocal
exit /b 0

:log
echo %LOG_TAG% [%date% %time%] %~1
goto :eof
